package com.zhaojonhy.zhaopangwb.Fragment;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;


import java.util.ArrayList;

/**
 * Created by Administrator on 2016/9/5.
 */

//fragment切换用同一个控制器所以就做成单例模式
public class FragmentController {

    private static final String TAG = FragmentController.class.getSimpleName() ;
    private FragmentActivity activity ;

    //处理hide和show显示隐藏
    //通过add把所有的fragment和activity相关联
    private int containerId ;
    private FragmentManager fm ;
    private ArrayList<Fragment> fragments ;
//创建一个本类对象的静态引用
    private static FragmentController controller ;
//提供一个获取对象的公有的静态方法
//    public static FragmentController getInstance(FragmentActivity activity , int containerId){
//
//        if(controller == null){
//            controller = new FragmentController(activity,containerId) ;
//        }
//        return controller ;
//    }
//私有化构造方法,防止在其他地方new本类对象
    public FragmentController(FragmentActivity activity , int containerId){

        this.containerId = containerId ;
        this.activity = activity ;
        fm = activity.getSupportFragmentManager();
        initFragment();
    }

    private void initFragment() {

        fragments = new ArrayList<Fragment>() ;
        fragments.add(new HomeFragment()) ;
        fragments.add(new MessageFragment()) ;
        fragments.add(new SearchFragment()) ;
        fragments.add(new UserFragment()) ;

       // FragmentTransaction对fragment进行添加,移除,替换,以及执行其他动作。
       // 从 FragmentManager 获得一个FragmentTransaction的实例 :
        FragmentTransaction ft = fm.beginTransaction() ;
        for(Fragment fragment : fragments){
            ft.add(containerId,fragment) ;
        }
        ft.commit() ;
    }

    public void showFragment(int position){

        hideFragments() ;
        Fragment fragment = new Fragment() ;
        fragment = fragments.get(position) ;
        FragmentTransaction ft = fm.beginTransaction() ;
        ft.show(fragment) ;
        ft.commit() ;

    }
//隐藏fragment对象
    public void hideFragments(){

        FragmentTransaction ft = fm.beginTransaction() ;
        for (Fragment fragment : fragments) {
            if( fragment != null ){
                ft.hide(fragment) ;
            }
        }
        ft.commitAllowingStateLoss() ;

    }

    public Fragment getFragment(int position){

        return fragments.get(position) ;
    }


}
